<template>
  <div class="product-management">
    <!-- 顶部操作栏 -->
    <div class="action-bar">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索商品名称或编号"
          @input="handleSearch"
        >
        <i class="fas fa-search"></i>
      </div>
      <div class="filters">
        <select v-model="categoryFilter">
          <option value="">全部分类</option>
          <option v-for="category in categories" :key="category" :value="category">
            {{ category }}
          </option>
        </select>
        <select v-model="statusFilter">
          <option value="">全部状态</option>
          <option value="active">上架</option>
          <option value="inactive">下架</option>
        </select>
      </div>
      <button class="add-btn" @click="showAddModal = true">
        <i class="fas fa-plus"></i>
        添加商品
      </button>
    </div>

    <!-- 商品列表 -->
    <div class="product-table">
      <table>
        <thead>
          <tr>
            <th>商品图片</th>
            <th>商品名称</th>
            <th>价格</th>
            <th>库存</th>
            <th>分类</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="product in filteredProducts" :key="product._id">
            <td>
              <img :src="product.images[0]" :alt="product.name" class="product-image">
            </td>
            <td>{{ product.name }}</td>
            <td>¥{{ product.price }}</td>
            <td>{{ product.stock }}</td>
            <td>{{ product.category }}</td>
            <td>
              <span class="status-tag" :class="product.status">
                {{ product.status === 'active' ? '上架' : '下架' }}
              </span>
            </td>
            <td>{{ formatDate(product.createdAt) }}</td>
            <td>
              <div class="action-buttons">
                <button class="edit-btn" @click="handleEdit(product)">
                  <i class="fas fa-edit"></i>
                </button>
                <button 
                  class="toggle-btn" 
                  :class="product.status"
                  @click="toggleStatus(product)"
                >
                  <i :class="product.status === 'active' ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
                </button>
                <button class="delete-btn" @click="handleDelete(product)">
                  <i class="fas fa-trash"></i>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button 
        :disabled="currentPage === 1"
        @click="currentPage--"
      >
        <i class="fas fa-chevron-left"></i>
      </button>
      <span>第 {{ currentPage }} 页</span>
      <button 
        :disabled="currentPage === totalPages"
        @click="currentPage++"
      >
        <i class="fas fa-chevron-right"></i>
      </button>
    </div>

    <!-- 添加/编辑商品弹窗 -->
    <div class="modal" v-if="showAddModal || showEditModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>{{ showEditModal ? '编辑商品' : '添加商品' }}</h3>
          <button class="close-btn" @click="closeModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="handleSubmit">
            <div class="form-group">
              <label>商品名称</label>
              <input type="text" v-model="formData.name" required>
            </div>
            <div class="form-group">
              <label>商品描述</label>
              <textarea v-model="formData.description" rows="3"></textarea>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>价格</label>
                <input type="number" v-model="formData.price" min="0" step="0.01" required>
              </div>
              <div class="form-group">
                <label>库存</label>
                <input type="number" v-model="formData.stock" min="0" required>
              </div>
            </div>
            <div class="form-group">
              <label>分类</label>
              <select v-model="formData.category" required>
                <option v-for="category in categories" :key="category" :value="category">
                  {{ category }}
                </option>
              </select>
            </div>
            <div class="form-group">
              <label>商品图片</label>
              <div class="image-uploader">
                <div 
                  v-for="(image, index) in formData.images" 
                  :key="index" 
                  class="image-preview"
                >
                  <img :src="image" :alt="`商品图片${index + 1}`">
                  <button type="button" class="remove-image" @click="removeImage(index)">
                    <i class="fas fa-times"></i>
                  </button>
                </div>
                <button type="button" class="add-image" @click="addImage">
                  <i class="fas fa-plus"></i>
                  添加图片
                </button>
              </div>
            </div>
            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="closeModal">取消</button>
              <button type="submit" class="submit-btn">
                {{ showEditModal ? '保存修改' : '添加商品' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div class="modal" v-if="showDeleteModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>确认删除</h3>
          <button class="close-btn" @click="showDeleteModal = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <p>确定要删除商品"{{ selectedProduct?.name }}"吗？此操作不可恢复。</p>
          <div class="form-actions">
            <button class="cancel-btn" @click="showDeleteModal = false">取消</button>
            <button class="delete-btn" @click="confirmDelete">确认删除</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { Product } from '@/types'
import api from '@/api'

// 状态变量
const products = ref<Product[]>([])
const searchQuery = ref('')
const categoryFilter = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const totalPages = ref(1)
const showAddModal = ref(false)
const showEditModal = ref(false)
const showDeleteModal = ref(false)
const selectedProduct = ref<Product | null>(null)

// 表单数据
const formData = ref({
  name: '',
  description: '',
  price: 0,
  stock: 0,
  category: '',
  images: [] as string[]
})

// 分类列表
const categories = [
  '手机数码',
  '电脑办公',
  '家用电器',
  '服装鞋包',
  '食品生鲜',
  '图书音像'
]

// 过滤商品列表
const filteredProducts = computed(() => {
  return products.value.filter(product => {
    const matchQuery = product.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchCategory = !categoryFilter.value || product.category === categoryFilter.value
    const matchStatus = !statusFilter.value || product.status === statusFilter.value
    return matchQuery && matchCategory && matchStatus
  })
})

// 格式化日期
const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

// 搜索处理
const handleSearch = () => {
  // 实现搜索逻辑
}

// 编辑商品
const handleEdit = (product: Product) => {
  selectedProduct.value = product
  formData.value = { ...product }
  showEditModal.value = true
}

// 切换商品状态
const toggleStatus = async (product: Product) => {
  try {
    const newStatus = product.status === 'active' ? 'inactive' : 'active'
    await api.patch(`/products/${product._id}/status`, { status: newStatus })
    product.status = newStatus
  } catch (error) {
    console.error('Failed to toggle product status:', error)
  }
}

// 删除商品
const handleDelete = (product: Product) => {
  selectedProduct.value = product
  showDeleteModal.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!selectedProduct.value) return

  try {
    await api.delete(`/products/${selectedProduct.value._id}`)
    products.value = products.value.filter(p => p._id !== selectedProduct.value?._id)
    showDeleteModal.value = false
  } catch (error) {
    console.error('Failed to delete product:', error)
  }
}

// 添加图片
const addImage = () => {
  // 实现图片上传逻辑
  formData.value.images.push('https://via.placeholder.com/200')
}

// 移除图片
const removeImage = (index: number) => {
  formData.value.images.splice(index, 1)
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (showEditModal.value && selectedProduct.value) {
      await api.put(`/products/${selectedProduct.value._id}`, formData.value)
      const index = products.value.findIndex(p => p._id === selectedProduct.value?._id)
      if (index !== -1) {
        products.value[index] = { ...selectedProduct.value, ...formData.value }
      }
    } else {
      const response = await api.post('/products', formData.value)
      products.value.unshift(response.data)
    }
    closeModal()
  } catch (error) {
    console.error('Failed to save product:', error)
  }
}

// 关闭弹窗
const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  selectedProduct.value = null
  formData.value = {
    name: '',
    description: '',
    price: 0,
    stock: 0,
    category: '',
    images: []
  }
}

// 获取商品列表
const fetchProducts = async () => {
  try {
    const response = await api.get('/products')
    products.value = response.data
    totalPages.value = Math.ceil(response.total / response.pageSize)
  } catch (error) {
    console.error('Failed to fetch products:', error)
  }
}

// 初始化
fetchProducts()
</script>

<style scoped>
.product-management {
  padding: 24px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box input {
  width: 100%;
  padding: 8px 32px 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.search-box i {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.filters {
  display: flex;
  gap: 16px;
}

.filters select {
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.add-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.product-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

th {
  background: #fafafa;
  font-weight: 500;
  color: #666;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.status-tag {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.status-tag.active {
  background: #f6ffed;
  color: #52c41a;
}

.status-tag.inactive {
  background: #fff2f0;
  color: #ff4d4f;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons button {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.edit-btn {
  background: #e6f7ff;
  color: #1890ff;
}

.toggle-btn {
  background: #f6ffed;
  color: #52c41a;
}

.toggle-btn.inactive {
  background: #fff2f0;
  color: #ff4d4f;
}

.delete-btn {
  background: #fff2f0;
  color: #ff4d4f;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

.pagination button {
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.pagination button:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  border: none;
  background: none;
  font-size: 18px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #666;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.image-uploader {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 16px;
}

.image-preview {
  position: relative;
  aspect-ratio: 1;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.remove-image {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #ff4d4f;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.add-image {
  aspect-ratio: 1;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  background: none;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #999;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 24px;
}

.cancel-btn {
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.submit-btn {
  padding: 8px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.delete-btn {
  padding: 8px 16px;
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style> 